//
//  TabScrollView.m
//
//  Created by vpabo on 16/3/19.
//  Copyright © 2016年 liubo. All rights reserved.
//

#import "TabScrollView.h"
#import "UIView+LayoutMethods.h"


#define MTab_Height 44
#define Line_Height 2

#define Title_Red_Color 0
#define Title_Green_Color 153
#define Title_Blue_Color 233

#define Title_Color JooColor(Title_Red_Color, Title_Green_Color, Title_Blue_Color, 1)
#define BG_Color JooColor(227, 227, 227, 1)

#define Scroll_Tag 2106


@interface TabScrollView ()<UIScrollViewDelegate>

// 标题数据
@property (nonatomic, strong) NSMutableArray *titleArr;
// 子界面
@property (nonatomic, strong) NSMutableArray *subViewArr;
// 蓝色线条
@property (nonatomic, strong) UIView *curLine;
// 按钮集合
@property (nonatomic, strong) NSMutableArray *btnArr;
// 内容区域
@property (nonatomic, strong) UIScrollView *tabScroll;
// 数量
@property (nonatomic) NSInteger itemCount;

// 宽 高
@property (nonatomic) float curW;
@property (nonatomic) float curH;

/** 之前的btn */
@property (nonatomic, strong) UIButton *tempBtn;
// 记录点，左右滑动，与此点进行比较
@property (nonatomic) int recordItem;
// 是否点击按钮
@property (nonatomic) BOOL isBtnClick;
/** 是否完成动画 */
@property (nonatomic) BOOL isAnimFinish;

@end


@implementation TabScrollView

#pragma mark - 外部方法

/**
 *  初始化方法,传入标题
 *
 *  @return
 */
-(id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        self.curW = frame.size.width;
        self.curH = frame.size.height;
        self.btnArr = [NSMutableArray array];
        self.titleArr = [NSMutableArray array];
        self.subViewArr = [NSMutableArray array];
        self.isAnimFinish = YES;
    }
    return self;
}

/**
 *  添加 标题 和 视图
 *
 *  @param title
 *  @param subView
 */
-(void)addTitle:(NSString *)title withView:(UIView *)subView
{
    if (title == nil) {
        title = @"默认";
    }
    
    if (subView == nil) {
        subView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.curW, self.curH-MTab_Height)];
        
        subView.backgroundColor = JooColor(arc4random()%255, arc4random()%255, arc4random()%255, 1);
    }
    [self.titleArr addObject:title];
    [self.subViewArr addObject:subView];
}

/**
 *  更新视图
 */
-(void)UpdateUI
{
    self.itemCount = self.titleArr.count;
    [self createSegment];
    [self createContentView];
}

/**
 *  设置选项卡
 *
 *  @param index 索引
 */
-(void)setSelectedIndex:(NSInteger) index
{
    [self.tabScroll setContentOffset:CGPointMake(index*self.curW, 0) animated:YES];
}


#pragma mark - 创建视图

/**
 *  创建头部切换标签视图
 */
-(void)createSegment
{
    // 添加按钮
    for (int i =0; i<self.itemCount; i++) {
        NSString *str = _titleArr[i];
        UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
        [btn setTitle:str forState:UIControlStateNormal];
        if (i == 0) {
            self.tempBtn = btn;
        }
        
        [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        btn.titleLabel.font = JooFont(15);
        [btn setBackgroundColor:[UIColor whiteColor]];
        btn.frame = CGRectMake(self.curW/self.itemCount*i, 0, self.curW/self.itemCount, MTab_Height);
        btn.tag = i;
        [self addSubview:btn];
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.btnArr addObject:btn];
    }
    
    // 设置选中的按钮
    [self.tempBtn setTitleColor:Title_Color  forState:UIControlStateNormal];
    self.tempBtn.transform = CGAffineTransformMakeScale(1.1, 1.1);
    
    // 添加 上方 灰色线
    UIView *grayTopLine = [[UIView alloc] init];
    grayTopLine.backgroundColor = BG_Color;
    grayTopLine.frame = CGRectMake(0, 0, self.curW, 1);
    [self addSubview:grayTopLine];
    
    // 添加 下方 灰色线
    UIView *grayBottomLine = [[UIView alloc] init];
    grayBottomLine.backgroundColor = BG_Color;
    grayBottomLine.frame = CGRectMake(0, MTab_Height-1, self.curW, 1);
    [self addSubview:grayBottomLine];
    
    // 添加 移动 蓝色块
    UIView *line = [[UIView alloc] init];
    line.backgroundColor = Title_Color;
    line.frame = CGRectMake(0, MTab_Height-Line_Height, self.curW/self.itemCount, Line_Height);
    [self addSubview:line];
    self.curLine = line;
}


/**
 *  创建内容视图
 */
-(void)createContentView
{
    UIScrollView *tabScroll = [[UIScrollView alloc] init];
    tabScroll.userInteractionEnabled = YES;
    tabScroll.frame = CGRectMake(0,MTab_Height, self.curW, self.curH-MTab_Height);
    tabScroll.pagingEnabled = YES;
    tabScroll.bounces = NO;
    tabScroll.showsHorizontalScrollIndicator = NO;
    tabScroll.delegate = self;
    tabScroll.tag = Scroll_Tag;
    tabScroll.contentSize = CGSizeMake(self.curW*self.itemCount, self.curH-MTab_Height);
    [self addSubview:tabScroll];
    self.tabScroll = tabScroll;
    
    
    //** 界面自定义 */
    for (int i= 0; i< self.itemCount; i++) {
        UIView *subView = self.subViewArr[i];
        subView.frame = CGRectMake(i*self.curW, subView.frame.origin.y, subView.frame.size.width, subView.frame.size.height);
        [tabScroll addSubview:subView];
    }
}


#pragma mark - 事件处理

/**
 *  按钮点击事件
 */
-(void)btnClick:(UIButton *)sender
{
    if (self.tempBtn == sender){
        return;
    }
    NSInteger item = sender.tag;
    [self changeBtnState:item];
    [self.tabDelegate selectedIndex:item];
}

/**
 *  改变按钮 颜色，大小，移动下面的线
 *
 *  @param index
 */
-(void)changeBtnState:(NSInteger)index
{
    
    if (!self.isAnimFinish) {
        return;
    }
    self.isAnimFinish = NO;
    
    UIButton *btn = self.btnArr[index];
    self.isBtnClick = YES;
    [UIView animateWithDuration:0.25 animations:^{
        self.curLine.x = index*self.curW/self.itemCount;
        btn.transform = CGAffineTransformMakeScale(1.1, 1.1);
        self.tempBtn.transform = CGAffineTransformMakeScale(1, 1);
        [btn setTitleColor:Title_Color forState:UIControlStateNormal];
        [self.tempBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    } completion:^(BOOL finished) {
        self.tempBtn = btn;
        self.isAnimFinish = YES;
    }];
    
    [self.tabScroll setContentOffset:CGPointMake(index*self.curW, 0) animated:NO];
}



#pragma mark - UIScrollView 代理事件
/**
 *  移动事件
 *
 *  @param scrollView
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (self.isBtnClick) {
        self.isBtnClick = NO;
        return;
    }
    
    if (scrollView.tag == Scroll_Tag) {
        float setX = scrollView.contentOffset.x;
        
        /**---  线移动 ---*/
        float moveX = setX/self.titleArr.count;
        self.curLine.x = moveX;
        
        
        /**---  计算移动比例 ---*/
        float itemWidth = self.curW/self.itemCount;
        float bl = fabs(moveX/itemWidth - self.recordItem);
        
        /**---  解决快速滑动，而造成ui的问题 ---*/
        if (bl>1) {
            bl -= 1;
            if (moveX/itemWidth > self.recordItem){
                self.recordItem++;
            }else{
                self.recordItem--;
            }
        }
        
        /**---  动态计算颜色，字体 ---*/
        UIButton *curBtn;
        UIButton *otherBtn;
        UIColor *curColor;
        UIColor *otherColor;
        CGAffineTransform curTransform;
        CGAffineTransform otherTransform;
        
        float compareWidth = self.recordItem*self.curW;
        
        curBtn = self.btnArr[self.recordItem];
        if (setX > compareWidth) {
            otherBtn = self.btnArr[self.recordItem+1];
        }else if(setX < compareWidth){
            otherBtn = self.btnArr[self.recordItem-1];
        }
        
        curColor = JooColor(Title_Red_Color, Title_Green_Color*(1-bl), Title_Blue_Color*(1-bl), 1);
        otherColor = JooColor(Title_Red_Color, Title_Green_Color*bl, Title_Blue_Color*bl, 1);
        
        curTransform = CGAffineTransformMakeScale(1+0.1*(1-bl), 1+0.1*(1-bl));
        otherTransform = CGAffineTransformMakeScale(1+0.1*bl, 1+0.1*bl);
        
        [curBtn setTitleColor:curColor forState:UIControlStateNormal];
        [otherBtn setTitleColor:otherColor forState:UIControlStateNormal];
        
        curBtn.transform = curTransform;
        otherBtn.transform = otherTransform;
    }

}

// 在拖动之前，记录item
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    float setX = scrollView.contentOffset.x;
    self.recordItem = setX/self.curW;
    NSLog(@"44444");
}


//减速停止了时执行，手触摸时执行执行
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView;
{
    int item = scrollView.contentOffset.x/self.curW;
    NSLog(@"选中第 %d 个",item);
    UIButton *btn = self.btnArr[item];
    self.tempBtn = btn;
    [self.tabDelegate selectedIndex:item];
    NSLog(@"333333");
}


- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    NSLog(@"1111");
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView
{
    NSLog(@"22222");
}


@end
